package types

import (
	"net"
	"sync"
)

// ConnPool 所有连接对象
type ConnPool struct {
	m sync.Map
}

func (c *ConnPool) Load(commId string) (conn net.Conn, ok bool) {
	var load any
	load, ok = c.m.Load(commId)

	if ok {
		conn = load.(net.Conn)
	} else {
		conn = nil
	}

	return
}

func (c *ConnPool) Store(commId string, conn net.Conn) {
	c.m.Store(commId, conn)
}

func (c *ConnPool) LoadOrStore(commId string, conn net.Conn) (actual net.Conn, loaded bool) {
	var store any
	store, loaded = c.m.LoadOrStore(commId, conn)

	if store != nil {
		actual = store.(net.Conn)
	}

	return
}

func (c *ConnPool) Delete(commId string) {
	c.m.Delete(commId)
}

func (c *ConnPool) Range(f func(commId string, value net.Conn) bool) {
	f1 := func(key, value interface{}) bool {
		return f(key.(string), value.(net.Conn))
	}
	c.m.Range(f1)
}
